
from django.test import override_settings
from django.views.decorators.clickjacking import xframe_options_exempt
from dataclasses import field
from ensurepip import bootstrap
from django.shortcuts import render
from app01 import models
from django import forms
from django.core.validators import ValidationError
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from app01.utils.bootstrape import BootStrapModelForm,BootStrapForm
from django.views.decorators.csrf import csrf_exempt
from app01.utils.pagination import Pagination
from app01.utils.encrypt import md5
from decimal import Decimal 

class ClientModelForm(BootStrapModelForm):
    class Meta:
        model=models.Client
        fields="__all__"

@csrf_exempt
@xframe_options_exempt
def client_info(request):
    queryset=models.Client.objects.all().order_by("-id")

    form=ClientModelForm()
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),
        'form':form
    }
  
    return render(request,'client_info.html',contxt)


class ClientEditModelForm(BootStrapModelForm):
    class Meta:
        model=models.Client
        fields=['cname','cmobile','caddr']

def client_edit(request,nid):
    row_obj=models.Client.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/client_info/")
    if request.method=="GET":
        form=ClientEditModelForm(instance=row_obj)
        return render(request,'change1.html',{'form':form,'title':'编辑'})
    form=ClientEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/client_info/")
    return render(request,'change1.html',{'form':form,'title':"编辑"})

def client_delete(request,nid):
    models.Client.objects.filter(id=nid).delete()
    return redirect('/client_info/')

@csrf_exempt
@xframe_options_exempt
def worker_info(request):
    queryset=models.Water_workers.objects.all().order_by("-id")

    form=ClientModelForm()
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),
        'form':form
    }
  
    return render(request,'worker_info.html',contxt)

class WorkerAddModelForm(BootStrapModelForm):
    confirm_password=forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(render_value=True)
        )
    class Meta:
        model=models.Water_workers
        fields=['wname','base_salary','commision','password','confirm_password']
        widgets={
            "password":forms.PasswordInput(render_value=True)
        }
    def clean_password(self):
        password=self.cleaned_data.get('password')
        return md5(password)
    def clean_confirm_password(self):
        password=self.cleaned_data.get('password')   
        confirm_password=md5(self.cleaned_data.get('confirm_password'))
        if password!=confirm_password:
            raise ValidationError('密码不一致')
        return confirm_password

def worker_add(request):
    if request.method=='GET':
        form=WorkerAddModelForm()   
        contxt={'title':'添加',
            'form':form
        }   
        return render(request,'change1.html',contxt)
    form=WorkerAddModelForm(request.POST)
    if form.is_valid():
        #通过验证的信息都在forms.cleaned_data
        form.save()
        return redirect("/worker_info/")
    return render(request,'change1.html',{'form':form,'title':'新建管理员'})

class WorkerEditModelForm(BootStrapModelForm):
    class Meta:
        model=models.Water_workers
        fields=['wname','base_salary','commision']

def worker_edit(request,nid):
    row_obj=models.Water_workers.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/worker_info/")
    if request.method=="GET":
        form=WorkerEditModelForm(instance=row_obj)
        return render(request,'change1.html',{'form':form,'title':'编辑'})
    form=WorkerEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/worker_info/")
    return render(request,'change1.html',{'form':form,'title':"编辑"})

class WorkerResetModelForm(BootStrapModelForm):
    confirm_password=forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(render_value=True)
        )
    class Meta:
        model=models.Water_workers
        fields=["password"]
        widgets={
            "password":forms.PasswordInput(render_value=True)
        }
    def clean_password(self):
        password=self.cleaned_data.get('password')
        md5_pwd=md5(password)
        exists=models.Water_workers.objects.filter(id=self.instance.pk,password=md5_pwd)
        if exists:
            raise ValidationError('不能与之前的密码相同')
        return md5(password)
    def clean_confirm_password(self):
        password=self.cleaned_data.get('password')   
        confirm_password=md5(self.cleaned_data.get('confirm_password'))
        if password!=confirm_password:
            raise ValidationError('密码不一致')
        return confirm_password

def worker_reset(request,nid):
    row_obj=models.Water_workers.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/worker_info/")
    title='重置密码-{}'.format(row_obj.wname)
    if request.method=='GET':
        form=WorkerResetModelForm()
        return render(request,'change1.html',{'form':form,'title':title})
    form=WorkerResetModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect('/worker_info/')
    return render(request,'change1.html',{'form':form,'title':title})

def worker_delete(request,nid):
    models.Water_workers.objects.filter(id=nid).delete()
    return redirect('/worker_info/')

@csrf_exempt
def worker_reserve(request):
    uid=request.GET.get("uid")
    wid=request.GET.get("id")
    wname=request.GET.get("name")
    oid=models.Order.objects.filter(id=uid).first().oid
    print(oid)
    if models.Order_examine.objects.filter(wid=wid,oid=oid):
        return JsonResponse({"status":False})
   
    models.Order.objects.filter(id=uid).update(state2=2)
    row_dict=models.Order.objects.filter(id=uid).values("oid",'cname','pname','num').first()
    models.Order_examine.objects.create(wid=wid,wname=wname,oid=row_dict.get("oid"),cname=row_dict.get("cname"),pname=row_dict.get("pname"),num=row_dict.get("num"),state3=2)
    return JsonResponse({"status":True})  


def admin_examine(request):
   
    queryset=models.Order_examine.objects.filter(state=1).order_by("id")

    form=ClientModelForm()
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),
        'form':form
    }
  
    return render(request,'admin_examine.html',contxt)

def admin_pass(request):
    uid=request.GET.get("uid")
    models.Order_examine.objects.filter(oid=uid).update(state=2,state1=3,state3=3)
    # models.Order.objects.filter(oid=uid).update(state3=3)
    return JsonResponse({"status":True})

def admin_no(request):
    uid=request.GET.get("uid")
    models.Order_examine.objects.filter(oid=uid).update(state=2,state3=4)
    # models.Order.objects.filter(id=uid).update(state3=4)
    return JsonResponse({"status":True})


def history(request):
    queryset=models.Order_examine.objects.filter(state1=2).order_by("-id")
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),

    }
    return render(request,'history.html',contxt)
    
def fare(request):
    total_list=[]
    total=Decimal(0)
    queryset2=models.Water_workers.objects.all()
    wid_list=list(models.Water_workers.objects.values('id'))
    for i in wid_list:
        base_salary=models.Water_workers.objects.get(id=i["id"]).base_salary
        models.Water_workers.objects.filter(id=i["id"]).update(salary=base_salary)
        if models.Order_examine.objects.filter(state1=2,wid=i["id"]):
            queryset=list(models.Order_examine.objects.filter(wid=i["id"],state1=2).values('wid', 'num'))
            commision=models.Water_workers.objects.get(id=queryset[0]['wid']).commision
            for obj in queryset:
                total = total + commision * Decimal(obj['num'])
            total=total+base_salary
            models.Water_workers.objects.filter(id=i["id"]).update(salary=total)
       
    page_obj=Pagination(request,queryset2)
    contxt={'queryset':page_obj.page_queryset,'page_string':page_obj.html()}
    return render(request,'fare.html',contxt)

def purify_water(request):
    num_list=list(models.Purify_water.objects.values("id","num"))
    print(num_list)
    id_list=[]
    for i in num_list:
        if i.get("num")<=0:
            models.Purify_water.objects.filter(id=i.get("id")).update(state=2)
    queryset2=models.Purify_water.objects.filter(state=2)
    queryset=models.Purify_water.objects.all()
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),
        'queryset2':queryset2,
    }
    return render(request,'purify_water.html',contxt)

class PurifyEditModelForm(BootStrapModelForm):
    class Meta:
        model=models.Purify_water
        fields=['pname','price','num','supplier']

def purify_add(request):
    if request.method=='GET':
        form=PurifyEditModelForm()   
        contxt={'title':'添加',
            'form':form
        }   
        return render(request,'change1.html',contxt)
    form=PurifyEditModelForm(request.POST)
    if form.is_valid():
        #通过验证的信息都在forms.cleaned_data
        form.save()
        return redirect("/Purify_water/")
    return render(request,'change1.html',{'form':form,'title':'添加'})

def purify_edit(request,nid):
    row_obj=models.Purify_water.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/Purify_water/")
    if request.method=="GET":
        form=PurifyEditModelForm(instance=row_obj)
        return render(request,'change1.html',{'form':form,'title':'编辑'})
    form=PurifyEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/Purify_water/")
    return render(request,'change1.html',{'form':form,'title':"编辑"})

def purify_delete(request,nid):
    models.Purify_water.objects.filter(id=nid).delete()
    return redirect('/purify_water/')

def purchase(request):
    num_list=list(models.Purify_water.objects.values("id","num"))
    print(num_list)
    id_list=[]
    for i in num_list:
        if i.get("num")<=0:
            id_list.append(i)

    # queryset=models.Purify_water.objects.filter(id>0)
    # print(queryset) 

def supplier(request):
    queryset=models.Supplier.objects.all()
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),

    }
    return render(request,'supplier.html',contxt)

class WaterEditModelForm():
    class Meta:
        model=models.Purify_water
        fields="__all__"
def water_edit(request,nid):
    row_obj=models.Purify_water.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/purify_water/")
    if request.method=="GET":
        form=WaterEditModelForm(instance=row_obj)
        return render(request,'change1.html',{'form':form,'title':'编辑'})
    form=WaterEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/purify_water/")
    return render(request,'change1.html',{'form':form,'title':"编辑"})


def chart_bar(request):
    name_list=list(models.Water_workers.objects.values("id",'wname'))
    nums_all=[]
    num_all=Decimal(0)
    wname_list=[]
    wid_list=[]
    for i in name_list:
        wname_list.append(i.get("wname"))
    
    for j in name_list:
        wid_list.append(j.get("id"))
    for k in wid_list:
        if models.Order_examine.objects.filter(wid=k,state1=2):
            num_list=list(models.Order_examine.objects.filter(wid=k,state1=2).values("num"))
            for m in num_list:
                num_all=num_all+m["num"]
            nums_all.append(num_all)
        nums_all.append(0)
    legend=["送水量"]
    series_list=[
        {
            "name": '累计送水量',
            "type": 'bar',
            "data": nums_all
        },
    ]
    xAxis=wname_list
    result={
        "status":True,
        "data":{
            "legend":legend,
            "series_list":series_list,
            "xAxis":xAxis
        }
        
    }
    return JsonResponse(result)

def admin_order(request):
   
    queryset=models.Order_examine.objects.filter(state=2).order_by("-id")
    page_obj=Pagination(request,queryset)
    contxt={'queryset':page_obj.page_queryset,
        'page_string':page_obj.html(),
        
    }
    return render(request,'admin_order.html',contxt)       

class SupplierEditModelForm(BootStrapModelForm):
    class Meta:
        model=models.Supplier
        fields=['sname','smobile']

def supplier_edit(request,nid):
    row_obj=models.Supplier.objects.filter(id=nid).first()
    if not row_obj:
        return redirect("/supplier/")
    if request.method=="GET":
        form=SupplierEditModelForm(instance=row_obj)
        return render(request,'change1.html',{'form':form,'title':'编辑'})
    form=SupplierEditModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/supplier/")
    return render(request,'change1.html',{'form':form,'title':"编辑"})

def supplier_delete(request,nid):
    models.Supplier.objects.filter(id=nid).delete()
    return redirect('/supplier/')

def supplier_add(request):
    if request.method=='GET':
        form=SupplierEditModelForm()   
        contxt={'title':'添加',
            'form':form
        }   
        return render(request,'change1.html',contxt)
    form=SupplierEditModelForm(request.POST)
    if form.is_valid():
        #通过验证的信息都在forms.cleaned_data
        form.save()
        return redirect("/supplier/")
    return render(request,'change1.html',{'form':form,'title':'添加'})

# def admin_order_delete(request,nid):
#     models.Supplier.objects.filter(id=nid).delete()
#     return redirect('/supplier/')
